<template>
  <div class="app-container">
    <!-- 数据查询区：表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="券名称" prop="ticketName">
        <el-input
          v-model="queryParams.ticketName"
          placeholder="请输入券名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="面值" prop="value">
        <el-input-number
          v-model="queryParams.value"
          placeholder="请输入面值"
          :min="0"
          :precision="2"
          controls-position="right"
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="ticketStatus">
        <el-select v-model="queryParams.ticketStatus" style="width: 200px" placeholder="请选择状态" @keyup.enter="handleQuery">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据操作区：按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" @click="handleDeleteBatch" :disabled="!multiple">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区：表格 -->
    <el-table v-loading="loading" :data="tickets" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="券编号" align="center" width="150" prop="ticketId" />
      <el-table-column label="券名称" align="center" prop="ticketName">
        <template #default="{row}">
          <span style="color: #1890ff">{{ row.ticketName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="面值(元)" align="center" width="120" prop="value">
        <template #default="{row}">
          {{ row.value.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" align="center" prop="packageName" />
      <el-table-column label="有效期" align="center" width="120" prop="validTime">
        <template #default="{row}">
          <el-tag :type="row.validTime === '永久有效' ? 'success' : 'warning'">
            {{ row.validTime }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100" prop="ticketStatus">
        <template #default="{row}">
          <el-tag :type="row.ticketStatus === '1' ? 'success' : 'danger'">
            {{ row.ticketStatus === '1' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" size="small" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button link type="primary" icon="View" size="small" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 数据编辑区：新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="券名称" prop="ticketName">
          <el-input v-model="form.ticketName" placeholder="请输入券名称" />
        </el-form-item>
        <el-form-item label="面值(元)" prop="value">
          <el-input-number 
            v-model="form.value" 
            :min="0" 
            :precision="2" 
            controls-position="right" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="套餐" prop="packageId">
          <el-select 
            v-model="form.packageId" 
            placeholder="请选择套餐" 
            style="width: 100%"
            @change="handlePackageChange"
          >
            <el-option
              v-for="item in packageOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格" prop="packagePrice">
          <el-input v-model="form.packagePrice" disabled />
        </el-form-item>
        <el-form-item label="有效期" prop="validTime">
          <el-select v-model="form.validTime" placeholder="请选择有效期" style="width: 100%">
            <el-option label="永久有效" value="永久有效" />
            <el-option label="30天" value="30天" />
            <el-option label="90天" value="90天" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="ticketStatus">
          <el-switch 
            v-model="form.ticketStatus" 
            active-value="1"
            inactive-value="0"
            active-text="上架" 
            inactive-text="下架" />
        </el-form-item>
        <el-form-item label="券描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入券描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
          <el-button @click="resetForm(formRef)" v-show="form.ticketId === undefined">重 置</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据查看区：抽屉 -->
    <el-drawer v-model="drawer" title="团购券信息" :with-header="false">
      <el-descriptions :title="ticketTitle" :column="2" border>
        <el-descriptions-item label="券编号">{{ ticket.ticketId }}</el-descriptions-item>
        <el-descriptions-item label="券名称">{{ ticket.ticketName }}</el-descriptions-item>
        <el-descriptions-item label="面值(元)">{{ ticket.value?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="套餐名称">{{ ticket.packageName }}</el-descriptions-item>
        <el-descriptions-item label="套餐价格">{{ ticket.packagePrice?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="有效期">
          <el-tag :type="ticket.validTime === '永久有效' ? 'success' : 'warning'">
            {{ ticket.validTime }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="ticket.ticketStatus === '1' ? 'success' : 'danger'">
            {{ ticket.ticketStatus === '1' ? '上架' : '下架' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="券描述">{{ ticket.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ ticket.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ ticket.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TicketDTO, QueryParams, RuleForm } from "@/views/market/management/types";
import { listAllTicket, listTicket, listTicketByPage, getTicketById, getTicketByName, addTicket, updateTicket, deleteTicket, deleteTicketBatch } from '@/api/ticket'

onMounted(() => {
  // 挂载后加载数据
  getList()
})

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>()

// 查询参数
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  ticketName: '',
  value: undefined,
  ticketStatus: ''
})
const queryParams = toRef(query)

// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getList()
}

/** ------------------数据展示区——表格-------------------- */
// 数据列表
const loading = ref<boolean>(false)  // table数据加载遮罩
const total = ref<number>(0) // table数据总数
const isEditMode = ref(false)

// table数据
const ticketData = reactive<TicketDTO[]>([]) 
const tickets = toRef(ticketData)

// 加载数据
const getList = async (params?: any) => {
  loading.value = true
  const query = params || queryParams.value
  /** 调用后端分页查询接口 */
  listTicketByPage(query).then(response => {
    tickets.value = response.data.list
    total.value = response.data.total
    loading.value = false
  })
}

/** ------------------数据展示区：数据选择-------------------- */
const ids = ref<string[]>([]) // 表单勾选的id
const single = ref<boolean>(false) // 勾选1个
const multiple = ref<boolean>(false) // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: TicketDTO[]) {
  ids.value = selection.map((item: TicketDTO) => item.ticketId)
  single.value = selection.length == 1
  multiple.value = selection.length >= 1 
}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val
  getList()
}

//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val
  getList()
}

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>()

const formData = reactive<RuleForm>({
  ticketName: '',
  value: 0,
  packageId: '',
  packageName: '',
  packagePrice: 0,
  validTime: '永久有效',
  ticketStatus: '1',
  description: ''
})
const form = toRef(formData)

// 套餐选项
const packageOptions = ref([
  { id: '1', name: '招牌双人牛排套餐', price: 129 },
  { id: '2', name: '水果沙拉套餐', price: 19 }
])

// 表单验证规则
const rules = reactive<FormRules<RuleForm>>({ 
  ticketName: [
    { required: true, message: '券名称不能为空', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '面值不能为空', trigger: 'blur' }
  ],
  packageId: [
    { required: true, message: '请选择套餐', trigger: 'change' }
  ],
  validTime: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
})

// 对话框数据
const title = ref('') // 对话框标题
const open = ref(false) //对话框打开

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {
      /** 调用后端新增和修改接口 */
      if (isEditMode.value) {
        updateTicket(form.value).then((response) => {
          ElMessage({ type: 'success', message: '修改数据成功' })
        })
      } else {
        addTicket(form.value).then((response) => {
          ElMessage({ type: 'success', message: '新增数据成功' })
        })
      }
      getList()
      open.value = false
    } else {
      console.log('表单验证未通过', fields) // 前台会自动提示errors
    }
  })
}

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 数据编辑区-->取消按钮
function cancel() {
  initForm()
  open.value = false
}

// 套餐选择变化
const handlePackageChange = (val: string) => {
  const selected = packageOptions.value.find(item => item.id === val)
  if (selected) {
    form.value.packageName = selected.name
    form.value.packagePrice = selected.price
  }
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
  form.value = {
    ticketName: '',
    value: 0,
    packageId: '',
    packageName: '',
    packagePrice: 0,
    validTime: '永久有效',
    ticketStatus: '1',
    description: ''
  }
}

// 数据操作区--> 新增按钮
function handleAdd() {
  isEditMode.value = false //标记为新增模式
  initForm()
  title.value = '新增团购券'
  open.value = true
}

// 数据操作区区--> 修改按钮
const handleUpdate = async (row: TicketDTO) => {
  isEditMode.value = true
  initForm()
  const id = row.ticketId || ids.value[0]

  /** 调用后端id查询接口*/
  getTicketById(id).then((response) => {
    form.value = response.data
    title.value = '修改团购券[' + id + ']'
    open.value = true
  })
}

// 数据操作区--> 删除按钮
async function handleDelete(row: any) {
  const id = row.ticketId
  ElMessageBox.confirm('是否删除编号为' + id + '的数据?', '警告')
    .then(() => {
      return deleteTicket(id)
    })
    .then(() => {
      getList()
      ElMessage({ type: 'success', message: '删除成功' })
    })
    .catch(() => { })
}

// 数据操作区--> 批量删除
async function handleDeleteBatch() {
  const ticketIds = ids.value
  ElMessageBox.confirm('是否批量删除编号为' + ticketIds + '的数据?', '警告')
    .then(() => {
      return deleteTicketBatch(ticketIds)
    })
    .then(() => {
      getList()
      ElMessage({ type: 'success', message: '批量删除成功' })
    })
    .catch(() => { })
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false)
const ticketTitle = ref<string>('');
const ticket = ref<TicketDTO>({
  ticketId: '',
  ticketName: '',
  value: 0,
  packageId: '',
  packageName: '',
  packagePrice: 0,
  validTime: '永久有效',
  ticketStatus: '1'
})

// 数据操作区--> 查看按钮
function handleView(row: TicketDTO) {
  getTicketById(row.ticketId).then(response => {
    ticket.value = response.data
    ticketTitle.value = '查看团购券数据[' + row.ticketId + ']'
  })
  drawer.value = true
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>